from google.appengine.ext import db

from lib.webapp import app, render_context, render, MJRequestHandler
from os.path import join

import lib.waypoints as wp

import sys
import logging

#from django import forms
from django import newforms as forms


from lib.webapp import app, check_admin

log = logging.getLogger(__name__)

class WPTypeForm( forms.Form ):
    
    wptype          = forms.CharField(widget=forms.HiddenInput(),required=False)
    name            = forms.CharField(max_length=60,required=True)
    desc            = forms.CharField(max_length=512,widget=forms.Textarea(attrs={'rows':'10','cols':'70'}),required=False)
    wptype_parent   = forms.CharField(widget=forms.HiddenInput(),required=False)

class ctl_WPTypes(MJRequestHandler):
 
    path = "/wptypes"
 
    def load_wptype(self):
      
        wptype = self.request.get( "wptype", None )
        log.debug( "wptype = %s" % type )

        if( None == wptype ):
            self.redirect( "/error?msg=no_wptype_key" )
            
            return False
            
        try:
            self.c.wpt = db.GqlQuery( "select * from WPType where __key__ = :1", db.Key(wptype)  ).fetch(1)[0]
            log.debug( "loaded wptype for %s" % wptype )
        except:
            self.redirect( "/error?msg=wrng_wptype_key" )
            return False

        return True      
 
    @check_admin
    def save(self):
        
        self.c.form = WPTypeForm( self.request )
        
        if( self.c.form.is_valid() ):

            wpt_key = self.c.form.clean_data["wptype"]
            wptp_key = self.c.form.clean_data["wptype_parent"]

            wpt = None
            
            if( wpt_key != "" ):
                if( not self.load_wptype() ):
                    return None

                self.c.wpt.name = self.c.form.clean_data["name"]

            else:        
                self.c.wpt = wp.WPType(name=self.c.form.clean_data["name"])

            self.c.wpt.desc = self.c.form.clean_data["desc"]
                
            self.c.wpt.put()
            self.redirect_index()
        else:
            return self.render( "/en/editwptype.html" )  
              
      
    @check_admin
    def edit(self):
        
        
        #load wptype
        if( self.load_wptype() ):
            log.debug( "edit a wptype" )
            self.c.form = WPTypeForm({\
                "name":self.c.wpt.name,\
                "desc":self.c.wpt.desc, \
                "wptype":self.c.wpt.key() } )
        else:
            self.redirect_index()
            return

        return self.render( "/en/editwptype.html" )  

    @check_admin
    def new(self):
        self.c.form = WPTypeForm()    
        return self.render( "/en/editwptype.html" )  

    def view(self):

        if( not self.load_wptype() ):
            return self.redirect_index()

        return self.render( "/en/viewwptype.html" )  

    def index(self):
      
        self.c.wptypes = wp.WPType.all().order( "name" )
        
      
        return self.render( "/en/listwptypes.html" )
      

    def __init__(self):
      
        MJRequestHandler.__init__(self)
      
        self.add_handler( "/save", self.save )
        self.add_handler( "/edit", self.edit )
        self.add_handler( "/new", self.new )
        self.add_handler( "/view", self.view, False )



app().add_handler( ctl_WPTypes.path + ".*", ctl_WPTypes )
